package auth

import (
	"cftgo/cftf/db"
	"cftgo/cftf/ginhelper"
	"errors"
	"login/internal/common/constant"
	"login/model"
	"unicode"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func isPureLetterAndNumber(s string) bool {
	for _, r := range s {
		if !(unicode.IsLetter(r) || unicode.IsDigit(r)) {
			return false
		}
	}
	return true
}

func (this *Auth) guestAuth(c *gin.Context, reqObj *reqBodyObj) {
	if !isPureLetterAndNumber(reqObj.Data) {
		ginhelper.RspErr(c, 3, "guest id has invalid character")
		return
	}
	if len(reqObj.Data) >= constant.MAX_OPENID_LENGTH {
		ginhelper.RspErr(c, 4, "guest id to long")
		return
	}
	var aidBindAccountModel = model.AidBindAccount{}
	result := db.GetOrmDb(constant.ACCOUNT_DB).First(&aidBindAccountModel, map[string]interface{}{
		"app_id":      reqObj.AppId,
		"plat_id":     reqObj.PlatId,
		"plat_openid": reqObj.Data,
	})
	if result.Error == nil {
		accModel := new(model.Account)
		result = db.GetOrmDb(constant.ACCOUNT_DB).First(&accModel, map[string]interface{}{
			"aid": aidBindAccountModel.Aid,
		})
		if result.Error == nil {
			this.rspAuthOk(c, accModel)
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	} else {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			this.createAccount(c, reqObj.AppId, reqObj.PlatId, reqObj.Data, nil)
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	}
}
